import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Tabs,
  Space,
  Button,
  Form,
  Row,
  Col,
  Input,
  message,
  Checkbox,
  Modal,
  Table,
} from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import {
  PlusOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  PrinterOutlined,
} from '@ant-design/icons';
import InspDtl from './components/inspDtl';
import request from '@/utils/request';
import { EmpSelect } from '@/components/FormItemSelect';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';
import PrintModal from '@/components/PrintModal';
import TempleteNonConf from '../PrintTemplete/TempleteNonConf';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/NonConf/';
const apiURL2 = '/api/services/app/NonConfDtl/';
const currentControl = 'NonConf';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [data, setData] = useState<any>({
    data: { conNum: '0', id: '0' },
    details: [],
  });
  const [defTab, setDefTab] = useState('1');
  const [freshNum, setFreshNum] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const formRef = useRef<any>(null);
  const inspDtlRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    formRef.current.setFieldsValue({ NonConf: data });
  }, []);


  const onFinish = (values: any) => {
    if (defTab === '1') {
      save(values.NonConf);
    } else {
      inspDtlRef.current.submit();
    }
  };

  const resetForm = () => {
    const data = {
      data: { conNum: '0', id: '0' },
      details: [],
    };
    formRef.current.resetFields();
    formRef.current.setFieldsValue({ NonConf: data.data });
    setData(data);
  };

  const save = (model: any) => {
    let act = 'Modify';
    const method = 'POST';
    if (model.id === '0') {
      act = 'New';
    }
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          getObj(response.result?.conNum);
        }
        setFreshNum(freshNum + 1);
        setLoading(false);
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const getObj = (value: any) => {
    if (!value) {
      return;
    }
    setLoading(true);
    request(apiURL + 'GetByNum', {
      method: 'GET',
      params: { num: value },
    }).then((response) => {
      if (response) {
        if (response.success) {
          const result = response.result;
          const NonConf = response.result.data;
          console.log(result);
          
          if (NonConf) {
            formRef.current.setFieldsValue({ NonConf });
            setData(result);
          }
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    if (data.data) {
      confirm({
        title: intl.formatMessage({ id: 'pages.warning' }),
        icon: <ExclamationCircleOutlined />,
        content: intl.formatMessage({ id: 'pages.delete.confirm' }),
        onOk() {
          props
            .dispatch({
              type: 'Abp/delBatch',
              payload: [data.data.id],
              control: currentControl,
            })
            .then(() => {
              resetForm();
              setFreshNum(freshNum + 1);
            });
        },
      });
    }
  };

  const switchModal = (visible: boolean, record: any = null) => {
    console.log(data);
    
    setVisible(visible);
  };

  const delDtl = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        props
          .dispatch({
            type: 'Abp/delBatch',
            payload: selectedRowKeys,
            control: 'NonConfDtl',
          })
          .then(() => {
            getObj(data.data.conNum);
            setFreshNum(freshNum + 1);
          });
      },
    });
  };

  const handleBatchConf = () => {
    let i = (data.details?.length?data.details?.length:0) + 1;
    if(!data.data || data.data.conNum === 0){
      message.error(intl.formatMessage({id: 'pages.confNum.required'}));
      return;
    }
    console.log(data.data);
    
    var arr: any = [];
    selectedRows.forEach((element: any) => {
      const obj = {
        ConNum: data.data.conNum,
        ConLine: i,
        DMRNum: element.DMRNum,
        Quantity: element.Quantity,
        PartNum: element.PartNum,
        PartDescription: element.PartDescription,
        IUM: element.IUM,
      };
      arr.push(obj);
      i++;
    });
    console.log(arr);
    request(apiURL2 + 'BatchDeal', {
      method: 'POST',
      data: arr,
    }).then((response) => {
      if (response) {
        if (response.success) {
          getObj(data.data.conNum);
          setVisible(false);
          setFreshNum(freshNum + 1);
        }
        setLoading(false);
      }
    });
  };

  const handlePrint = () => {
    setVisible2(true);
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.conNum" />,
      dataIndex: 'conNum',
    },
    {
      title: <FormattedMessage id="pages.orderLine" />,
      dataIndex: 'conLine',
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'conQty',
    },
    {
      title: <FormattedMessage id="pages.completeQty" />,
      dataIndex: 'completeQty',
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
    },
    {
      title: <FormattedMessage id="pages.openline" />,
      dataIndex: 'openLine',
      key: 'openLine',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (_selectedRowKeys: any) => {
      setSelectedRowKeys(_selectedRowKeys);
    },
  };

  const rowSelection2 = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setSelectedRows(selectedRows);
    },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={<FormattedMessage id="menu.Inspect.confEntry" />}
          extra={
            <Space>
              <Button key="1" type="primary" onClick={resetForm}>
                <span>
                  <FormattedMessage id="pages.reset" />
                </span>
              </Button>
              <Button key="2" type="primary" htmlType="submit" loading={loading}>
                <span>
                  <FormattedMessage id="pages.save" />
                </span>
              </Button>
              <Button
                key="4"
                type="dashed"
                danger
                icon={<CloseOutlined />}
                onClick={delObj}
                disabled={data.data.id === '0'}
              >
                <span>
                  <FormattedMessage id="pages.delete" />
                </span>
              </Button>
              <Button key="5" type="ghost" icon={<PrinterOutlined />} onClick={handlePrint}>
                <span>
                  <FormattedMessage id="pages.print" />
                </span>
              </Button>
              <QuickMenu path="/Inspect/confEntry" icon="icon-todo_list" title="pages.ConfEntry" />
            </Space>
          }
        >
          <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
            <TabPane tab={<FormattedMessage id="pages.summary" />} key="1">
              <Row>
                <Col span={12}>
                  <Form.Item name={['NonConf', 'id']} hidden={true}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['NonConf', 'conNum']}
                    label={<FormattedMessage id="pages.conNum" />}
                    rules={[{ required: true, message: <FormattedMessage id="pages.conNum.required" /> }]}
                  >
                    <Input
                      style={{ width: 200 }}
                      onBlur={(e: any) => getObj(e.target.value)}
                      disabled
                    />
                  </Form.Item>
                  <EmpSelect
                    showSearch
                    width={200}
                    name={['NonConf', 'entryPerson']}
                    label={<FormattedMessage id="pages.entryPerson" />}
                    params={{ deptCode: 'QA' }}
                  />
                </Col>
                <Col span={12}>
                  <Form.Item
                    name={['NonConf', 'commentText']}
                    label={<FormattedMessage id="pages.commentText" />}
                  >
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 5 }}>
                    <Input.Group compact>
                      <Form.Item name={['NonConf', 'openCon']} valuePropName="checked">
                        <Checkbox disabled>
                          <FormattedMessage id="pages.openline" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.detail" />} key="2">
              <Table
                rowKey="id"
                size="small"
                columns={columns}
                loading={loading}
                dataSource={data.details}
                rowSelection={rowSelection}
                onRow={(rec) => {
                  return {
                    onDoubleClick: () => {
                      switchModal(true, rec);
                    },
                  };
                }}
                footer={() => (
                  <Space>
                    <Button type="dashed" icon={<PlusOutlined />} onClick={() => switchModal(true)}>
                      <span>
                        <FormattedMessage id="pages.newDetail" />
                      </span>
                    </Button>
                    <Button
                      type="dashed"
                      danger
                      icon={<CloseOutlined />}
                      onClick={delDtl}
                      disabled={selectedRowKeys.length <= 0}
                    >
                      <span>
                        <FormattedMessage id="pages.delete" />
                      </span>
                    </Button>
                  </Space>
                )}
              />
            </TabPane>
          </Tabs>
        </Card>
      </Form>

      <OperpQuery
        sysReportName="ReportNonConf"
        scroll={{ x: 'max-content', y: '200px' }}
        freshNum={freshNum}
        callback={(e) => getObj(e.ConNum)}
      />

      <Modal
        title={<FormattedMessage id="pages.batchDeal" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => switchModal(false)}
        footer={
          <Button type="primary" onClick={handleBatchConf} disabled={selectedRows.length <= 0}>
            <FormattedMessage id="pages.submit" />
          </Button>
        }
        width={880}
        bodyStyle={{ padding: '0px' }}
      >
        <OperpQuery
          sysReportName="DMRSearch"
          scroll={{ x: 'max-content', y: '200px' }}
          rowSelection={rowSelection2}
        />
      </Modal>
      <Modal
        width={1024}
        title={<FormattedMessage id="pages.print" />}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <PrintModal>
          <TempleteNonConf data={data} configData={props.currentConfig} />
        </PrintModal>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  currentConfig: user.currentConfig,
}))(ViewPage);
